﻿using BaseBll;
using BaseWebApi.App_Start;
using BaseWebApi.Common;
using BaseWebApi.Models;
using Common;
using Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Net.Http;
using System.Web.Http;

namespace BaseWebApi.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [ControllerGroup(groupName: "User", useage: "系统设置-用户管理")]
    public class UserController : BaseController
    {
        private JWTPlayloadInfo playload;

        private readonly UserBll _instance;

        /// <summary>
        /// 构造方法
        /// </summary>
        public UserController()
        {
            _instance = UserBll.Instance;
        }

        /// <summary>
        /// 分页查询用户信息
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页尺寸</param>
        /// <param name="userName">姓名</param>
        /// <param name="gender">性别</param>
        /// <param name="deptId">部门id</param>
        /// <param name="userAccount">账户</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetPageList(int pageIndex, int pageSize, string userName = "", int gender = 0, int deptId = 0, string userAccount = "")
        {
            string strWhere = "";
            if (!string.IsNullOrEmpty(userName))
            {
                strWhere += " and t1.UserName like '%" + userName + "%'";
            }
            if (gender == 1 || gender == 2)
            {
                strWhere += " and t1.Gender = " + gender;
            }
            if (deptId > 0)
            {
                strWhere += " and t1.DeptId = " + deptId;
            }
            if (!string.IsNullOrEmpty(userAccount))
            {
                strWhere += " and t1.UserAccount = '" + userAccount + "'";
            }

            DataTable dt = _instance.GetPageList(pageSize, pageIndex, strWhere, "t1.CreateTime", out int records);
            int totalPages = PageHelper.GetPageCount(pageSize, records);
            return JsonHelper.SuccessJson(CommonOperation.DataTable2JArray(dt), pageIndex, totalPages, records);
        }

        /// <summary>
        /// 根据ID获取实体对象
        /// </summary>
        /// <param name="ID">数据表ID</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetModel(int ID)
        {
            if (ID > 0)
            {
                Users model = _instance.GetModelById(ID);
                if (model != null)
                {
                    return JsonHelper.SuccessJson(JsonHelper.ModelToJObject(model));
                }
                else
                {
                    return JsonHelper.FailJson("数据不存在");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误");
            }
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage AddUser([FromBody] Users model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            //验证各字段合法性
            string msg = "";
            try
            {
                bool isOk = _instance.VerifyModel(model, ref msg);
                if (isOk)
                {

                    // 默认字段
                    model.CreateTime = DateTime.Now;
                    model.CreateUser = playload.UserName;
                    // 初始密码： 123
                    string initPassword = "123";
                    // 随机盐值
                    // 设置计算成本 BCrypt的计算成本是一个对数值，表示为2的幂次。例如，如果计算成本为10，则实际的迭代次数是2的10次幂，1024次
                    int cost = 5;
                    string salt = BCrypt.Net.BCrypt.GenerateSalt(cost);
                    string hashedPassword = BCrypt.Net.BCrypt.HashPassword(initPassword, salt);
                    model.UserPwd = hashedPassword;
                    int res = _instance.AddUser(model);
                    if (res > 0)
                    {
                        LogHelper.LogAction(playload, Constant.SysModule.User, Constant.ActionEnum.Add, "新增用户");
                        return JsonHelper.SuccessJson("添加成功");
                    }
                    else
                    {
                        LogHelper.LogWarn(playload, Constant.SysModule.User, Constant.ActionEnum.Add, "新增用户");
                        return JsonHelper.FailJson("添加失败");

                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.User, Constant.ActionEnum.Add, "新增用户");
                throw;
            }
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdateUser([FromBody] Users model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                if (model.ID <= 0)
                {
                    return JsonHelper.ErrorJson("参数错误");
                }
                bool isExist = _instance.IsExist(" and ID=" + model.ID);
                if (!isExist)
                {
                    return JsonHelper.ErrorJson("不存在该数据");
                }
                //验证各字段合法性
                string msg = "";
                bool isOk = _instance.VerifyModel(model, ref msg);
                if (isOk)
                {

                    // 默认字段
                    model.UpdateTime = DateTime.Now;
                    model.UpdateUser = playload.UserName;
                    int res = _instance.UpdateUser(model);
                    if (res > 0)
                    {
                        LogHelper.LogAction(playload, Constant.SysModule.User, Constant.ActionEnum.Edit, "修改用户");
                        return JsonHelper.SuccessJson("修改成功");
                    }
                    else
                    {
                        LogHelper.LogWarn(playload, Constant.SysModule.User, Constant.ActionEnum.Edit, "修改用户");
                        return JsonHelper.FailJson("修改失败");

                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.User, Constant.ActionEnum.Edit, "修改用户");
                throw;
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeleteUser(string id)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];

            try
            {
                if (string.IsNullOrEmpty(id))
                {
                    return JsonHelper.ErrorJson("参数错误");
                }

                string[] ids = id.Split(',');

                List<string> delId = new List<string>(ids);

                // 什么情况下的用户不允许删除 TODO

                int result = _instance.DeleteUser(delId, playload.UserName);
                if (result > 0)
                {
                    LogHelper.LogAction(playload, Constant.SysModule.User, Constant.ActionEnum.Delete, "删除用户");
                    return JsonHelper.SuccessJson("删除成功");
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.User, Constant.ActionEnum.Delete, "删除用户");
                    return JsonHelper.FailJson("删除失败");

                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.User, Constant.ActionEnum.Delete, "删除用户");
                throw;
            }
        }

        /// <summary>
        /// 启用/禁用
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdateStatus(int id, int status)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (id <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }

            if (status != 1 && status != 2)
            {
                return JsonHelper.ErrorJson("参数错误");
            }

            string strStatus = status == 1 ? "启用用户" : "禁用用户";

            try
            {
                // 判断是否存在该记录
                Users model = _instance.GetModelById(id);
                if (model == null)
                {
                    return JsonHelper.ErrorJson("数据不存在，请刷新重试");
                }
                int result = _instance.UpdateStatus(id, status, playload.UserName);
                if (result > 0)
                {
                    LogHelper.LogAction(playload, Constant.SysModule.User, Constant.ActionEnum.Enabled, strStatus);
                    return JsonHelper.SuccessJson(strStatus + "成功");
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.User, Constant.ActionEnum.Enabled, strStatus);
                    return JsonHelper.FailJson(strStatus + "失败");

                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.User, Constant.ActionEnum.Enabled, strStatus);
                throw;
            }

        }

        /// <summary>
        /// 用户认证
        /// </summary>
        /// <param name="id">id（多个id用 ， 分割）</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage AuditUser(string id)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (string.IsNullOrEmpty(id))
            {
                return JsonHelper.ErrorJson("参数错误");
            }

            try
            {

                int result = _instance.AuditUser(id);
                if (result > 0)
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.User, "用户认证", Constant.ActionEnum.Audit, Constant.StatusEnum.Success));
                    return JsonHelper.SuccessJson("认证成功");
                }
                else
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.User, "用户认证", Constant.ActionEnum.Audit, Constant.StatusEnum.Fail));
                    return JsonHelper.FailJson("认证失败");

                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.User, "用户认证" + ":" + ex.Message, Constant.ActionEnum.Audit, Constant.StatusEnum.Exception), ex);
                throw ex;
            }

        }
    }
}
